package app.fugema.shop.main.login.view;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextPaint;
import android.text.TextWatcher;
import android.text.style.ClickableSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;

import com.base.common.netBeanPackage.BaseApiResult;
import com.base.common.netBeanPackage.LiveDataWrapper;
import com.base.common.utils.OnClickCheckedUtil;
import com.base.common.utils.UIUtils;
import com.base.common.utils.VerifyUtils;
import com.base.common.utils.span.SpanUtils;
import com.base.common.view.base.BaseFragment;
import com.base.common.viewmodel.BaseViewObserver;
import app.fugema.shop.R;
import app.fugema.shop.databinding.LoginVerificationFragmentBinding;
import app.fugema.shop.main.login.vm.LoginVM;

public class LoginVerificationFragment extends BaseFragment<LoginVerificationFragmentBinding, LoginVM> {

    private int cont = 60;//倒计时


    @Override
    protected LoginVerificationFragmentBinding initDataBinding(LayoutInflater inflater, ViewGroup container)
    {
        return DataBindingUtil.inflate(inflater, R.layout.login_verification_fragment, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState)
    {
        super.onViewCreated(view, savedInstanceState);

        binding.etPhoneNO.requestFocus();
        binding.tvPasswordLogin.setOnClickListener(new OnClickCheckedUtil() {
            @Override
            public void onClicked(View view) {
                if (getActivity() instanceof LoginActivity) {
                    LoginActivity loginActivity = (LoginActivity) getActivity();
                    loginActivity.setCurrentItem(1);
                }
            }
        });

        binding.tvContent.setText("同意" + UIUtils.getString(R.string.app_name));
        binding.rtvVerification.setOnClickListener(new OnClickCheckedUtil() {
            @Override
            public void onClicked(View view) {
                String err = viewModel.checkedPhone(binding.etPhoneNO.getText().toString());
                if (err == null) {
                    getVerfyCode();
                } else {
                    binding.etPhoneNO.setError(err);
                }
            }
        });


        binding.rtvLogin.setOnClickListener(new OnClickCheckedUtil() {
            @Override
            public void onClicked(View view) {
                login();
            }
        });

        binding.tvRegister.setOnClickListener(new OnClickCheckedUtil() {
            @Override
            public void onClicked(View view) {
                RegisterActivity.lunch(mActivity);
                mActivity.finish();
            }
        });
        binding.etPhoneNO.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                stateChange(s.toString());
            }
        });

        VerifyUtils.onTextChangedPhone(binding.etPhoneNO);

        String s = binding.etPhoneNO.getText().toString().trim();
        if (s.length() == 0) {
            binding.rtvLogin.setEnabled(false);
            binding.rtvLogin.setAlpha(0.6f);
        }

        binding.llCheckedText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                binding.ctvCheckedText.setChecked(!binding.ctvCheckedText.isChecked());
                if (binding.ctvCheckedText.isChecked()) {
                    binding.ctvCheckedText.setBackgroundResource(R.mipmap.ic_radio_checked);
                } else {
                    binding.ctvCheckedText.setBackgroundResource(R.mipmap.ic_radio_unchecked);
                }
                stateChange(binding.etPhoneNO.getText().toString().trim());
            }
        });

        SpanUtils.with(binding.tvContent)
                .append("同意" + UIUtils.getString(R.string.app_name))
                .append("《用户服务协议》")
                .setClickSpan(new ClickableSpan() {
                    @Override
                    public void updateDrawState(@NonNull TextPaint ds) {
                        super.updateDrawState(ds);
                        ds.setColor(0xff2892E4);
                        ds.setUnderlineText(false);
                    }

                    @Override
                    public void onClick(@NonNull View widget) {
                        UserAgreementActivity.lunch(getActivity(), true);
                    }
                })
                .append("和")
                .append("《用户隐私协议》")
                .setClickSpan(new ClickableSpan() {
                    @Override
                    public void updateDrawState(@NonNull TextPaint ds) {
                        super.updateDrawState(ds);
                        ds.setColor(0xff2892E4);
                        ds.setUnderlineText(false);
                    }

                    @Override
                    public void onClick(@NonNull View widget) {
                        UserAgreementActivity.lunch(getActivity(), false);
                    }
                })
                .create();

    }

    private void stateChange(String phone) {
        if (VerifyUtils.checkPhoneNumber(phone) && binding.ctvCheckedText.isChecked()) {
            binding.rtvLogin.setEnabled(true);
            binding.rtvLogin.setAlpha(1f);
        } else {
            binding.rtvLogin.setEnabled(false);
            binding.rtvLogin.setAlpha(0.6f);
        }
    }

    /**
     * 获取验证码
     */
    public void getVerfyCode()
    {
        // 绑定手机验证码
        viewModel.getBindTelVerfyCode(binding.etPhoneNO.getText().toString() ,"userKey","imgCode","imgId").observe(this, new BaseViewObserver<LiveDataWrapper<BaseApiResult>>() {
            @Override
            protected void onSuccess(LiveDataWrapper<BaseApiResult> data)
            {
                binding.rtvVerification.setEnabled(false);
                cont = 60;
                binding.rtvVerification.setText(cont + "s");
                binding.etPassWord.requestFocus();
                binding.rtvVerification.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        cont--;
                        if (cont > 0) {
                            binding.rtvVerification.setText(cont + "s");
                            binding.rtvVerification.postDelayed(this, 1000);
                        } else {
                            binding.rtvVerification.setEnabled(true);
                            binding.rtvVerification.setText("获取验证码");
                        }

                    }
                }, 1000);
            }
        });
    }


    public void login()
    {
        String phone = binding.etPhoneNO.getText().toString();
        String code = binding.etPassWord.getText().toString();
        String err = viewModel.checkedErrStr(viewModel.checkedPhone(phone), viewModel.checkedCode(code));
        if (err == null)
        {
            /*
            viewModel.verifyCodeLogin(phone, code).observe(this, new BaseViewObserver<LiveDataWrapper<UserInfo>>(getActivity()) {
                @Override
                protected void onSuccess(LiveDataWrapper<UserInfo> data) {
                    UIUtils.showToastSafes("登录成功");
                    mActivity.finish();
                }
            });
            */
        }
        else
        {
            UIUtils.showToastSafes(err);
        }

    }


}
